﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Spread.Common.Features.Sample;
using GrapeCity.Spreadsheet;
using FarPoint.Win.Spread;
using GrapeCity.CalcEngine;

namespace Spread.Calculation.Features
{
    public partial class ZetaCalculator : BaseSampleControl
    {
        public ZetaCalculator()
        {
            InitializeComponent();
            fpSpread2.AddCustomFunction(new ZetaFunction());
            formulaTextBox1.Attach(fpSpread2);
            fpSpread2.StatusBarVisible = true;
        }
        private bool GetInputValues(ref double initval, ref double incr, ref int rc, ref long iter)
        {
            if (!double.TryParse(textBoxStart.Text, out initval))
            {
                MessageBox.Show("Please enter a double value for Start Value.");
                textBoxStart.Focus();
                return false;
            }
            if (!double.TryParse(textBoxIncrement.Text, out incr))
            {
                MessageBox.Show("Please enter a double value for Increment.");
                textBoxIncrement.Focus();
                return false;
            }
            if (!int.TryParse(textBoxCount.Text, out rc))
            {
                MessageBox.Show("Please enter an integer value for Count.");
                textBoxCount.Focus();
                return false;
            }
            long.TryParse(textBoxIter.Text, out iter);
            return true;
        }
        /// <summary>
        /// Returns the number format speifying the number of decimal places used for increment.
        /// </summary>
        /// <returns>
        /// The number format specifying the number of decimal places used for increment.
        /// </returns>
        /// <remarks>
        /// The calculator formats the first column using the number of decimal places for increment.
        /// </remarks>
        private string GetIncrementNumberFormat()
        {
            double incr = 0.1;
            if (!double.TryParse(textBoxIncrement.Text, out incr))
                return "0.0";
            StringBuilder sb = new StringBuilder();
            sb.Append("0.");
            while (incr < 1)
            {
                sb.Append("0");
                incr *= 10;
            }
            return sb.ToString();
        }
        /// <summary>
        /// Handle the "Calculate" button click.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <remarks>
        /// This event handler reinitialized the worksheet with the newly-generated Zeta calculation table.
        /// This code sets the formula to calculate ZETA as an array formula, and the spreadsheet calculates the result
        /// once, and sets the result to the range all at once using an array.
        /// The actual calculation is handled inside the custom function that is active (ZetaFunction or ZetaFunctionInfo).
        /// The title bar text is updated at the end with timing and call count information about the custom function execution.
        /// </remarks>
        private void buttonCalculate_Click(object sender, EventArgs e)
        {
            double initval = 0.0;
            double incr = 0.01;
            int rc = 12000;
            long iter = 10000;
            if (!GetInputValues(ref initval, ref incr, ref rc, ref iter))
                return;
            fpSpread2.SuspendLayout();
            Cursor = Cursors.WaitCursor;
            Text = "Calculating, please wait...";
            // inialize sheet with Zeta calculation table headers
            SheetView sheet = fpSpread2.ActiveSheet;
            sheet.Reset();
            sheet.RowCount = rc + 1;
            sheet.ColumnCount = 5;
            sheet.ReferenceStyle = FarPoint.Win.Spread.Model.ReferenceStyle.R1C1;
            sheet.Cells[0, 0].Text = "bi";
            sheet.Cells[0, 1].Text = "Re( ζ(0.5+bi) )";
            sheet.Cells[0, 2].Text = "Im( ζ(0.5+bi) )";
            sheet.Cells[0, 3].Text = "ζ(0.5+bi)";
            sheet.Cells[0, 4].Text = "IMABS( ζ(0.5+bi) )";
            sheet.Cells[0, 0, 0, 4].HorizontalAlignment = CellHorizontalAlignment.Center;
            // apply built-in styles for table header cells
            IWorkbook workbook = fpSpread2.AsWorkbook();
            workbook.ActiveSheet.Cells[0, 0, 0, 4].ApplyStyle(BuiltInStyle.Percent20Accent3);
            workbook.ActiveSheet.Cells[0, 0, 0, 4].ApplyStyle(BuiltInStyle.Heading3);
            // initialize the values to be calculated
            for (int r = 1; r <= rc; r++)
                sheet.Cells[r, 0].Value = initval + incr * r;
            // format the cells to show the number decimal places appropriate for increment
            fpSpread2.AsWorkbook().Worksheets[0].Cells[1, 0, rc, 0].NumberFormat = GetIncrementNumberFormat();
            // create the formula to calculate the ZETA function along the critical line Re = 0.5 for the 
            // set of points starting with the initial value and using the specified increment and iterations
            string formula = "ZETA(0.5,RC1," + rc.ToString().Trim() + "," + incr.ToString().Trim() + "," + iter.ToString().Trim() + ")";
            sheet.Cells[1, 1, rc, 2].FormulaArray = formula;
            // apply the COMPLEX function to the two values returned for the real (in column 1) and imaginary (in column 2) parts to get the resulting complex number calculated
            sheet.Cells[1, 3, rc, 3].Formula = "COMPLEX(RC2,RC3)";
            // apply IMABS function to resulting complex number -- this is equivalent to SQRT(RC2*RC2+RC3*RC3) and computes the length of the complex vector
            // IMABS values less than increment are considered "close" to a root and highlighted if the value is a local minimum
            sheet.Cells[1, 4, rc, 4].Formula = "IMABS(RC4)";
            // set column widths
            sheet.SetColumnWidth(0, (int)sheet.GetPreferredColumnWidth(0));
            sheet.SetColumnWidth(1, 150);
            sheet.SetColumnWidth(2, 150);
            sheet.SetColumnWidth(3, (int)sheet.GetPreferredColumnWidth(3));
            sheet.SetColumnWidth(4, (int)sheet.GetPreferredColumnWidth(4));
            // enable auto filter on the range
            workbook.ActiveSheet.Cells[0, 0, rc, 4].AutoFilter();
            // freeze first row from scrolling to keep table headers visible
            sheet.FrozenRowCount = 1;
            // renumber row headings 
            sheet.StartingRowNumber = 0;
            // clear the text in the first row header
            sheet.RowHeader.Cells[0, 0].Text = " ";
            // map the clipboard shortcut keys to special actions that copy only visible values as text
            // (so the sheet can be filtered and copy/paste works as expected)
            fpSpread2.GetInputMap(InputMapMode.WhenFocused).Put(new Keystroke(Keys.C, Keys.Control), SpreadActions.ClipboardCopyAsStringSkipHidden);
            fpSpread2.GetInputMap(InputMapMode.WhenFocused).Put(new Keystroke(Keys.Insert, Keys.Control), SpreadActions.ClipboardCopyAsStringSkipHidden);
            // create a conditional format to highlight the root (local minima IMABS < increment) values with yellow
            string conditionformula = "AND(RC5<" + incr.ToString() + ",RC5<R[1]C5,RC5<R[-1]C5)";
            FormulaConditionalFormattingRule formulaRule = new FormulaConditionalFormattingRule(conditionformula);
            formulaRule.BackColor = System.Drawing.Color.Yellow;
            sheet.SetConditionalFormatting(1, 0, rc, 5, new IConditionalFormattingRule[] { formulaRule });
            // cleanup, update window text with function call count and timing stats, enable filter roots button'
            fpSpread2.ResumeLayout();
            Cursor = Cursors.Default;
            if (checkBoxFunctionInfo.Checked)
                Text = "Zeta Calculation Complete! [ZetaFunctionInfo Call #" + ZetaFunctionInfo.cnt.ToString() + " in " + (ZetaFunctionInfo.t2 - ZetaFunctionInfo.t1).ToString() + "]";
            else
                Text = "Zeta Calculation Complete! [ZetaFunction Call #" + ZetaFunction.cnt.ToString() + " in " + (ZetaFunction.t2 - ZetaFunction.t1).ToString() + "]";
            buttonFilterRootsOnly.Enabled = true;
        }
        /// <summary>
        /// Apply a filter on the range to show only the root values.
        /// Creates a color filter for the first column in the worksheet.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonFilterRootsOnly_Click(object sender, EventArgs e)
        {
            IWorkbook workbook = fpSpread2.AsWorkbook();
            IWorksheet worksheet = workbook.ActiveSheet;
            Fill fill = new Fill(GrapeCity.Spreadsheet.Color.FromKnownColor(GrapeCity.Core.KnownColor.Yellow));
            worksheet.Cells[0, 0, worksheet.RowCount - 1, 4].AutoFilter(0, fill);
        }
        /// <summary>
        /// Toggles between using the new-style calculation function ZetaFunction and the old-style calculation function ZetaFunctionInfo.
        /// The new-style calculation function is recommended as it is slightly faster and easier to use than the old-style calculation function,
        /// which must be wrapped internally using GrapeCity.CalcEngine APIs to work in the new GrapeCity.CalcEngine.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkBoxFunctionInfo_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBoxFunctionInfo.Checked)
                // this method is marked obsolete and deprecated -- you should port your old FunctionInfo class to a Function class
                fpSpread2.ActiveSheet.AddCustomFunction(new ZetaFunctionInfo());
            else
                fpSpread2.AddCustomFunction(new ZetaFunction());
        }
        /// <summary>
        /// Event handler for the LeaveCell event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <remarks>
        /// This event handler enables and disables the GoalSeek button based on whether the active row is a highlighted root value.
        /// </remarks>
        private void fpSpread2_LeaveCell(object sender, LeaveCellEventArgs e)
        {
            IWorkbook workbook = fpSpread2.AsWorkbook();
            // get the interior color of the cell becoming active, enable goal seek button if it's a highlighted root value
            GrapeCity.Spreadsheet.Color c = workbook.ActiveSheet.Cells[e.NewRow, e.NewColumn].DisplayFormat.Interior.Color;
            if (c.Equals(GrapeCity.Spreadsheet.Color.FromKnownColor(GrapeCity.Core.KnownColor.Yellow)))
                buttonGoalSeek.Enabled = true;
            else
                buttonGoalSeek.Enabled = false;
        }
        /// <summary>
        /// Do a high-precision goal seek to 4 decimal places
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <remarks>
        /// The spreadsheet has built-in GoalSeek logic, but that logic is limited to 2 decimal places.
        /// This function uses the CalculationEngine to perform a goal seek to 4 decimal places.
        /// </remarks>
        private void buttonGoalSeek_Click(object sender, EventArgs e)
        {
            DateTime t2, t1 = DateTime.Now; // for timing the goal-seek
            IWorkbook wb = fpSpread2.AsWorkbook();
            CalculationEngine calcengine = wb.WorkbookSet.CalculationEngine;
            IWorksheet ws = wb.ActiveSheet;
            SheetView sheet = fpSpread2.ActiveSheet;
            double initval = 0.0;
            double incr = 0.01;
            int rc = 12000;
            long iter = 10000;
            int row = sheet.ActiveRowIndex;
            int cnt, cnt2; // for counting the number of ZETA function calls performed during goal-seek
            double maxchange; // current decimal place of search
            string formula, formulaNext; // formula for value and formula for next value to be tested
            IValue result, resultNext; // calculated result of formula for value and formula for next value
            // temp variables for calculating IMABS of result and resultNext
            double temp, temp1, temp2, tempNext, tempNext1, tempNext2;
            bool nextDecimalPlace; // flag for moving to next decimal place
            double value; // current value being tested
            // save initial ZETA call count
            if (checkBoxFunctionInfo.Checked)
                cnt = ZetaFunctionInfo.cnt;
            else
                cnt = ZetaFunction.cnt;
            if (!GetInputValues(ref initval, ref incr, ref rc, ref iter))
                return;
            // force 100K iterations for improved accuracy
            iter = 100000;
            // do goal seek on the cell [row, 0]:
            value = Math.Round((double)ws.Cells[row, 0].Value, 1) + 0.04; // start with value XXX.X4
            ws.Cells[row, 0].NumberFormat = "0.0000"; // format cell for 4 decimal places
            // my implementation for goal seek:
            Cursor = Cursors.WaitCursor;
            for (maxchange = 0.01; maxchange > 1e-5; maxchange *= 0.1)
            { // start changing the hundredths place, then move on to each sucessive decimal place until maxchange = 1e-10
                nextDecimalPlace = false; // reset flag 
                // calculate value
                formula = "ZETA(0.5," + value.ToString().Trim() + ",1,0," + iter.ToString().Trim() + ")";
                result = calcengine.Evaluate(formula, ws, new GrapeCity.Spreadsheet.CellReference(row, 1));
                temp1 = result.GetValuesArray()[0, 0].GetNumber();
                temp2 = result.GetValuesArray()[0, 1].GetNumber();
                // calculate absolute values of results
                temp = Math.Sqrt(temp1 * temp1 + temp2 * temp2);
                do
                { // next value (value + maxchange) using CalculationEngine.Evaluate
                    formulaNext = "ZETA(0.5," + (value + maxchange).ToString().Trim() + ",1,0," + iter.ToString().Trim() + ")";
                    resultNext = calcengine.Evaluate(formulaNext, ws, new GrapeCity.Spreadsheet.CellReference(row, 1));
                    tempNext1 = resultNext.GetValuesArray()[0, 0].GetNumber();
                    tempNext2 = resultNext.GetValuesArray()[0, 1].GetNumber();
                    // calculate absolute values of results
                    tempNext = Math.Sqrt(tempNext1 * tempNext1 + tempNext2 * tempNext2);
                    if (tempNext < temp)
                    {
                        value += maxchange; // next value is closer, increment value and continue checking next higher value
                        temp = tempNext;
                    }
                    else
                    { // next value is not closer, check previous value(s)
                        do
                        { // calculate previous value
                            formulaNext = "ZETA(0.5," + (value - maxchange).ToString().Trim() + ",1,0," + iter.ToString().Trim() + ")";
                            resultNext = calcengine.Evaluate(formulaNext, ws, new GrapeCity.Spreadsheet.CellReference(row, 1));
                            tempNext1 = resultNext.GetValuesArray()[0, 0].GetNumber();
                            tempNext2 = resultNext.GetValuesArray()[0, 1].GetNumber();
                            // calculate absolute value
                            tempNext = Math.Sqrt(tempNext1 * tempNext1 + tempNext2 * tempNext2);
                            if (tempNext < temp)
                            { // previous value is closer, decrement value and continue checking next previous value
                                value -= maxchange;
                                temp = tempNext;
                            }
                            else
                            { // previous value is not closer, current value is closest -- continue to next decimal place
                                nextDecimalPlace = true;
                                // decrement current decimal place value by 1 to avoid rounding errors, then make the new last decimal place a 4
                                value = value + 4 * (maxchange / 10);
                            }
                        } while (!nextDecimalPlace);
                    }
                } while (!nextDecimalPlace);
            }
            // discard last digit
            value = Math.Truncate(value * 10000) / 10000;
            // cleanup
            t2 = DateTime.Now;
            Cursor = Cursors.Default;
            if (checkBoxFunctionInfo.Checked)
                cnt2 = ZetaFunctionInfo.cnt;
            else
                cnt2 = ZetaFunction.cnt;
            sheet.Cells[row, 0].Value = value;
            sheet.Columns[0].Width = sheet.GetPreferredColumnWidth(0);
            MessageBox.Show("Zero Value: " + value.ToString() + "\r\nCalculation completed in " + (t2 - t1).ToString() + " with " + (cnt2 - cnt).ToString() + " calls to ZETA function.");
        }
    }
}

//
//ZetaCalculator.Designer.cs
//

namespace Spread.Calculation.Features
{
    partial class ZetaCalculator
    {
        /// <summary> 
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary> 
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ZetaCalculator));
            this.panel1 = new System.Windows.Forms.Panel();
            this.checkBoxFunctionInfo = new System.Windows.Forms.CheckBox();
            this.buttonFilterRootsOnly = new System.Windows.Forms.Button();
            this.formulaTextBox1 = new FarPoint.Win.Spread.FormulaTextBox();
            this.buttonGoalSeek = new System.Windows.Forms.Button();
            this.buttonCalculate = new System.Windows.Forms.Button();
            this.textBoxIter = new System.Windows.Forms.TextBox();
            this.label4 = new System.Windows.Forms.Label();
            this.textBoxCount = new System.Windows.Forms.TextBox();
            this.label3 = new System.Windows.Forms.Label();
            this.textBoxIncrement = new System.Windows.Forms.TextBox();
            this.label2 = new System.Windows.Forms.Label();
            this.textBoxStart = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            //this.fpSpread2 = new FarPoint.Win.Spread.FpSpread(FarPoint.Win.Spread.LegacyBehaviors.None, ((System.IO.MemoryStream)(resources.GetObject("resource1"))));
            this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
            this.fpSpread2 = new FarPoint.Win.Spread.FpSpread(FarPoint.Win.Spread.LegacyBehaviors.None, ((object)(resources.GetObject("pnlMain.Controls"))));
            this.fpSpread2_Sheet1 = this.fpSpread2.GetSheet(0);
            this.pnlMain.SuspendLayout();
            this.panel1.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.fpSpread2)).BeginInit();
            
            this.SuspendLayout();
            // 
            // pnlMain
            // 
            this.pnlMain.Controls.Add(this.fpSpread2);
            this.pnlMain.Size = new System.Drawing.Size(588, 387);
            // 
            // pnlControls
            // 
            this.pnlControls.Size = new System.Drawing.Size(195, 387);
            // 
            // panel1
            // 
            this.panel1.Controls.Add(this.checkBoxFunctionInfo);
            this.panel1.Controls.Add(this.buttonFilterRootsOnly);
            this.panel1.Controls.Add(this.formulaTextBox1);
            this.panel1.Controls.Add(this.buttonGoalSeek);
            this.panel1.Controls.Add(this.buttonCalculate);
            this.panel1.Controls.Add(this.textBoxIter);
            this.panel1.Controls.Add(this.label4);
            this.panel1.Controls.Add(this.textBoxCount);
            this.panel1.Controls.Add(this.label3);
            this.panel1.Controls.Add(this.textBoxIncrement);
            this.panel1.Controls.Add(this.label2);
            this.panel1.Controls.Add(this.textBoxStart);
            this.panel1.Controls.Add(this.label1);
            this.panel1.Dock = System.Windows.Forms.DockStyle.Top;
            this.panel1.Location = new System.Drawing.Point(0, 0);
            this.panel1.Name = "panel1";
            this.panel1.Size = new System.Drawing.Size(784, 63);
            this.panel1.TabIndex = 0;
            // 
            // checkBoxFunctionInfo
            // 
            this.checkBoxFunctionInfo.AutoSize = true;
            this.checkBoxFunctionInfo.Location = new System.Drawing.Point(12, 12);
            this.checkBoxFunctionInfo.Name = "checkBoxFunctionInfo";
            this.checkBoxFunctionInfo.Size = new System.Drawing.Size(129, 17);
            this.checkBoxFunctionInfo.TabIndex = 12;
            this.checkBoxFunctionInfo.Text = "Use ZetaFunctionInfo";
            this.toolTip1.SetToolTip(this.checkBoxFunctionInfo, "Check this box to use the old FarPoint.CalcEngine.CalcFunction type to implement " +
        "the custom ZETA function instead of the new GrapeCity.CalcEngine.Function type.");
            this.checkBoxFunctionInfo.UseVisualStyleBackColor = true;
            this.checkBoxFunctionInfo.CheckedChanged += new System.EventHandler(this.checkBoxFunctionInfo_CheckedChanged);
            // 
            // buttonFilterRootsOnly
            // 
            this.buttonFilterRootsOnly.Enabled = false;
            this.buttonFilterRootsOnly.Location = new System.Drawing.Point(585, 37);
            this.buttonFilterRootsOnly.Name = "buttonFilterRootsOnly";
            this.buttonFilterRootsOnly.Size = new System.Drawing.Size(92, 22);
            this.buttonFilterRootsOnly.TabIndex = 11;
            this.buttonFilterRootsOnly.Text = "Filter Roots Only";
            this.toolTip1.SetToolTip(this.buttonFilterRootsOnly, "Click this button to filter the rows in the spreadsheet to show only the root val" +
        "ues found, which are highlighted yellow.");
            this.buttonFilterRootsOnly.UseVisualStyleBackColor = true;
            this.buttonFilterRootsOnly.Click += new System.EventHandler(this.buttonFilterRootsOnly_Click);
            // 
            // formulaTextBox1
            // 
            this.formulaTextBox1.Location = new System.Drawing.Point(12, 37);
            this.formulaTextBox1.Multiline = false;
            this.formulaTextBox1.Name = "formulaTextBox1";
            this.formulaTextBox1.Size = new System.Drawing.Size(567, 19);
            this.formulaTextBox1.TabIndex = 10;
            this.toolTip1.SetToolTip(this.formulaTextBox1, "The formula in the active cell shows in this control and can be edited.");
            // 
            // buttonGoalSeek
            // 
            this.buttonGoalSeek.Enabled = false;
            this.buttonGoalSeek.Location = new System.Drawing.Point(683, 37);
            this.buttonGoalSeek.Name = "buttonGoalSeek";
            this.buttonGoalSeek.Size = new System.Drawing.Size(92, 22);
            this.buttonGoalSeek.TabIndex = 9;
            this.buttonGoalSeek.Text = "GoalSeek Root";
            this.toolTip1.SetToolTip(this.buttonGoalSeek, "Click this button to perform a custom goal seek on the selected root value to 9 d" +
        "ecimal places. You must select a root value in the spreadsheet to use this butto" +
        "n.");
            this.buttonGoalSeek.UseVisualStyleBackColor = true;
            this.buttonGoalSeek.Click += new System.EventHandler(this.buttonGoalSeek_Click);
            // 
            // buttonCalculate
            // 
            this.buttonCalculate.Location = new System.Drawing.Point(683, 12);
            this.buttonCalculate.Name = "buttonCalculate";
            this.buttonCalculate.Size = new System.Drawing.Size(92, 20);
            this.buttonCalculate.TabIndex = 8;
            this.buttonCalculate.Text = "Calculate";
            this.buttonCalculate.UseVisualStyleBackColor = true;
            this.buttonCalculate.Click += new System.EventHandler(this.buttonCalculate_Click);
            // 
            // textBoxIter
            // 
            this.textBoxIter.Location = new System.Drawing.Point(607, 12);
            this.textBoxIter.Name = "textBoxIter";
            this.textBoxIter.Size = new System.Drawing.Size(70, 20);
            this.textBoxIter.TabIndex = 7;
            this.textBoxIter.Text = "10000";
            this.toolTip1.SetToolTip(this.textBoxIter, "Number of iterations to calculate convergent series.  Higher values result in gre" +
        "ater precision, but take longer to calcuate.");
            // 
            // label4
            // 
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(548, 13);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(53, 13);
            this.label4.TabIndex = 6;
            this.label4.Text = "Iterations:";
            // 
            // textBoxCount
            // 
            this.textBoxCount.Location = new System.Drawing.Point(471, 11);
            this.textBoxCount.Name = "textBoxCount";
            this.textBoxCount.Size = new System.Drawing.Size(70, 20);
            this.textBoxCount.TabIndex = 5;
            this.textBoxCount.Text = "1000";
            this.toolTip1.SetToolTip(this.textBoxCount, "Number of points to calculate along the critical line Re = 1/2.");
            // 
            // label3
            // 
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(427, 13);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(38, 13);
            this.label3.TabIndex = 4;
            this.label3.Text = "Count:";
            // 
            // textBoxIncrement
            // 
            this.textBoxIncrement.Location = new System.Drawing.Point(352, 10);
            this.textBoxIncrement.Name = "textBoxIncrement";
            this.textBoxIncrement.Size = new System.Drawing.Size(69, 20);
            this.textBoxIncrement.TabIndex = 3;
            this.textBoxIncrement.Text = "0.1";
            this.toolTip1.SetToolTip(this.textBoxIncrement, "Increment between successive values of ZETA calulated along the critical line Re " +
        "= 1/2.");
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(289, 14);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(57, 13);
            this.label2.TabIndex = 2;
            this.label2.Text = "Increment:";
            // 
            // textBoxStart
            // 
            this.textBoxStart.Location = new System.Drawing.Point(213, 10);
            this.textBoxStart.Name = "textBoxStart";
            this.textBoxStart.Size = new System.Drawing.Size(70, 20);
            this.textBoxStart.TabIndex = 1;
            this.textBoxStart.Text = "14.0";
            this.toolTip1.SetToolTip(this.textBoxStart, "The initial value for the imaginary component of the first point to calculate alo" +
        "ng the critical line.");
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(145, 14);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(62, 13);
            this.label1.TabIndex = 0;
            this.label1.Text = "Start Value:";
            // 
            // fpSpread2
            // 
            this.fpSpread2.AccessibleDescription = "";
            this.fpSpread2.Location = new System.Drawing.Point(0, 63);
            this.fpSpread2.Dock = System.Windows.Forms.DockStyle.Fill;
            this.fpSpread2.Name = "fpSpread2";
            this.fpSpread2.Size = new System.Drawing.Size(784, 387);
            this.fpSpread2.TabIndex = 1;
            this.fpSpread2.LeaveCell += new FarPoint.Win.Spread.LeaveCellEventHandler(this.fpSpread2_LeaveCell);
            // 
            // fpSpread2
            // 
        
            // 
            // ZetaCalculator
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Controls.Add(this.fpSpread2);
            this.Controls.Add(this.panel1);
            this.Name = "ZetaCalculator";
            this.Size = new System.Drawing.Size(784, 450);
            this.Controls.SetChildIndex(this.panel1, 0);
            this.Controls.SetChildIndex(this.fpSpread2, 0);
            this.pnlMain.ResumeLayout(false);
            this.panel1.ResumeLayout(false);
            this.panel1.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.fpSpread2)).EndInit();
          
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Panel panel1;
        private System.Windows.Forms.Button buttonCalculate;
        private System.Windows.Forms.TextBox textBoxIter;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.TextBox textBoxCount;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.TextBox textBoxIncrement;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.TextBox textBoxStart;
        private System.Windows.Forms.Label label1;
        private FarPoint.Win.Spread.FpSpread fpSpread2;
        private FarPoint.Win.Spread.SheetView fpSpread2_Sheet1;
        private System.Windows.Forms.Button buttonGoalSeek;
        private FarPoint.Win.Spread.FormulaTextBox formulaTextBox1;
        private System.Windows.Forms.Button buttonFilterRootsOnly;
        private System.Windows.Forms.CheckBox checkBoxFunctionInfo;
        private System.Windows.Forms.ToolTip toolTip1;
      
    }
}

//
//ZetaFunction.cs
//

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using GrapeCity.CalcEngine;

namespace Spread.Calculation.Features
{
    internal sealed class ZetaFunction : Function
    {   // keep count of function calls
        internal static int cnt = 0;
        // time calculation
        internal static DateTime t1;
        internal static DateTime t2;
        /// <summary>
        /// Create the ZetaFunction.
        /// </summary>
        public ZetaFunction() : base("ZETA", 4, 5, FunctionAttributes.Array)
        { // minimum args 4, maximum args 5, returns array value
        }
        /// <summary>
        /// Evaluate the ZETA function.
        /// </summary>
        /// <param name="args">IArguments specifying arguments passed to ZETA</param>
        /// <param name="result">IValue for returning calculation result</param>
        protected override void Evaluate(IArguments args, IValue result)
        {
            cnt++; // increment function call counter
            t1 = DateTime.Now; // start timing evaluation
            long l = 10000L; // default to 10K iterations if not specified
            // get function arguments
            double d = args[0].GetPrimitiveValue(args.EvaluationContext).GetNumber();  // real part
            double d1 = args[1].GetPrimitiveValue(args.EvaluationContext).GetNumber(); // imaginary part
            long count = (long)args[2].GetPrimitiveValue(args.EvaluationContext).GetNumber(); // number of points to calculate
            double incr = args[3].GetPrimitiveValue(args.EvaluationContext).GetNumber(); // increment between points
            if (args.Count > 4) // iterations is optional
                l = (long)args[4].GetPrimitiveValue(args.EvaluationContext).GetNumber();
            IValuesArray array = result.CreateValuesArray((int)count, 2); // create array to return values
            double[,] arr = new double[count, 2]; // create local array to calculate values (can't set values to IValuesArray from another thread)
            // do the ZETA calculation in a Task using Parallel.For for better performance
            Task t = new Task(delegate
            {
                Parallel.For(0, count, i =>
                {
                    var d2 = 0.0;
                    var d3 = 0.0;
                    var d4 = 0.0;
                    var d5 = 0.0;
                    var dd1 = d1 + i * incr;
                    for (var l1 = 1; l1 <= l; l1++)
                    { // calculate Dirichlet Eta series partial sum of l iterations
                        var d6 = 2 * l1 - 1;
                        var d7 = 2 * l1;
                        var d14 = 0.0;
                        var d15 = 0.0;
                        var d16 = 0.0;
                        var d8 = (dd1 * Math.Log(d6)) % 6.2831853071795862;
                        var d9 = (dd1 * Math.Log(d7)) % 6.2831853071795862;
                        var d10 = -d;
                        var d11 = Math.Pow(d6, d10);
                        var d12 = Math.Pow(d7, d10);
                        d2 += d11 * Math.Cos(d8) - d12 * Math.Cos(d9);
                        d3 += d12 * Math.Sin(d9) - d11 * Math.Sin(d8);
                        d4 += Math.Pow(d6, -0.5) * Math.Cos(d8) - Math.Pow(d7, -0.5) * Math.Cos(d9);
                        d14 = Math.Pow(d7, -0.5) * Math.Sin(d9);
                        d15 = Math.Pow(d6, -0.5);
                        d16 = Math.Sin(d8);
                        d5 += d14 - d15 * d16;
                    }
                    // calculate Zeta from Eta value
                    var d17 = 1.0 - Math.Pow(2, 1.0 - d) * Math.Cos(d1 * Math.Log(2));
                    var d18 = Math.Pow(2, 1.0 - d) * Math.Sin(d1 * Math.Log(2));
                    var d19 = (d17 * d2 + d18 * d3) / (Math.Pow(d17, 2) + Math.Pow(d18, 2));
                    var d20 = (d17 * d3 - d18 * d2) / (Math.Pow(d17, 2) + Math.Pow(d18, 2));
                    Interlocked.Exchange(ref arr[i, 0], d19);
                    Interlocked.Exchange(ref arr[i, 1], d20);
                });
            });
            t.RunSynchronously();  // need to run this task synchronously on the UI thread
            // copy values from arr to the IValuesArray
            for (int i = 0; i < count; i++)
            {
                array[i, 0].SetValue(arr[i, 0]);
                array[i, 1].SetValue(arr[i, 1]);
            }
            result.SetValue(array); // set result -- this is important! If you don't return a result, then the cells remain marked dirty and Evaluate will be called again...
            t2 = DateTime.Now; // time calculation
        }
    }
}

//
//ZetaFunctionInfo.cs
//

using FarPoint.CalcEngine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Spread.Calculation.Features
{
    internal sealed class ZetaFunctionInfo : FunctionInfo
    {   // keep count of function calls
        internal static int cnt = 0;
        // time calculation
        internal static DateTime t1;
        internal static DateTime t2;
        // required overrides for FunctionInfo
        public override string Name => "ZETA";
        public override int MinArgs => 4;
        public override int MaxArgs => 5;
        /// <summary>
        /// Evaluate the ZETA function.
        /// </summary>
        /// <param name="args">Array of object containing function arguments</param>
        /// <returns>ArrayResult object containing calculated results</returns>
        public override object Evaluate(object[] args)
        {
            cnt++;
            t1 = DateTime.Now;
            int l = 10000;
            double d = CalcConvert.ToDouble(args[0]);  // real part
            double d1 = CalcConvert.ToDouble(args[1]); // imaginary part
            int count = CalcConvert.ToInt(args[2]); // number of points to calculate
            double incr = CalcConvert.ToDouble(args[3]); // increment between points
            if (args.Length > 4)
                l = CalcConvert.ToInt(args[4]); // iterations
            double[,] arr = new double[count, 2]; // create array to return values
            // do the ZETA calculation in a Task using Parallel.For for better performance
            Task t = new Task(delegate
            {
                Parallel.For(0, count, i =>
                {
                    var d2 = 0.0;
                    var d3 = 0.0;
                    var d4 = 0.0;
                    var d5 = 0.0;
                    var dd1 = d1 + i * incr;
                    for (var l1 = 1; l1 <= l; l1++)
                    {
                        var d6 = 2 * l1 - 1;
                        var d7 = 2 * l1;
                        var d14 = 0.0;
                        var d15 = 0.0;
                        var d16 = 0.0;
                        var d8 = (dd1 * Math.Log(d6)) % 6.2831853071795862;
                        var d9 = (dd1 * Math.Log(d7)) % 6.2831853071795862;
                        var d10 = -1 * d;
                        var d11 = -1 * 0.5;
                        var d12 = Math.Pow(d6, d10);
                        var d13 = Math.Pow(d7, d10);
                        d2 += d12 * Math.Cos(d8) - d13 * Math.Cos(d9);
                        d3 += d13 * Math.Sin(d9) - d12 * Math.Sin(d8);
                        d4 += Math.Pow(d6, d11) * Math.Cos(d8) - Math.Pow(d7, d11) * Math.Cos(d9);
                        d14 = Math.Pow(d7, d11) * Math.Sin(d9);
                        d15 = Math.Pow(d6, d11);
                        d16 = Math.Sin(d8);
                        d5 += d14 - d15 * d16;
                    }
                    var d17 = 1.0 - Math.Pow(2, 1.0 - d) * Math.Cos(d1 * Math.Log(2));
                    var d18 = Math.Pow(2, 1.0 - d) * Math.Sin(d1 * Math.Log(2));
                    var d19 = (d17 * d2 + d18 * d3) / (Math.Pow(d17, 2) + Math.Pow(d18, 2));
                    var d20 = (d17 * d3 - d18 * d2) / (Math.Pow(d17, 2) + Math.Pow(d18, 2));
                    Interlocked.Exchange(ref arr[i, 0], d19);
                    Interlocked.Exchange(ref arr[i, 1], d20);
                });
            });
            t.RunSynchronously(); // need to run this task synchronously on the UI thread
            t2 = DateTime.Now;
            return new ArrayResult(arr); // return as ArrayResult (see below)
        }
    }
    /// <summary>
    /// Class inheriting from FarPoint.CalcEngine.CalcArray used to return the array result.
    /// </summary>
    /// <remarks>
    /// The old calculation engine (FarPoint.CalcEngine.dll) required implemnting a class to return an array of values.
    /// The CalcArray abstract class provides the base type for implementing a wrapper around the array to return.
    /// </remarks>
    public class ArrayResult : CalcArray
    {
        double[,] values;
        public ArrayResult(double[,] values)
        {
            if (values == null)
                values = new double[0, 0];
            this.values = values;
        }
        public override int RowCount => values.GetUpperBound(0) - values.GetLowerBound(0) + 1;
        public override int ColumnCount => values.GetUpperBound(1) - values.GetLowerBound(1) + 1;
        public override object GetValue(int row, int column)
        {
            return values[row, column];
        }
    }
}

